﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using BooksOnline.Models.Entities;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace UpdateBooksOnlineDBSchema
{
    class Program
    {
        private static Configuration configuration;
        private static ISessionFactory CreateSessionFactory()
        {
            return
                Fluently
                    .Configure()
                    .Database(MsSqlConfiguration
                            .MsSql2005
                            .ConnectionString("Password=Welcome@123;Persist Security Info=True;" +
                                              "User ID=sa;Initial Catalog=BooksOnline;Data Source=UNIVERSE"))
                    .Mappings(a => a.FluentMappings.AddFromAssemblyOf<Book>())
                    .ExposeConfiguration(c => configuration =  c.AddAssembly(typeof(Book).Assembly))
                    .BuildSessionFactory();
        }

        private static void BuildSchema(ISession session)
        {
            SchemaExport export = new SchemaExport(configuration);
            export.Execute(true, true, false, session.Connection, null);
        }

        private static void UpdateSchema()
        {
            ISessionFactory sessionFactory = CreateSessionFactory();
            var session = sessionFactory.OpenSession();
            BuildSchema(session);
        }

        static void Main(string[] args)
        {
            try
            {
                UpdateSchema();
                Console.WriteLine("The database schema is updated successfully...");
            }
            catch
            {
                Console.WriteLine("The database schema udpate failed...");
            }
            finally
            {
                Console.ReadLine();    
            }
            
        }
    }
}
